<script setup>
import {useTabStore} from "@/store/tabs.js";
import {watch} from "vue";
import {useRoute, useRouter} from "vue-router";

const tabStore = useTabStore();
const route = useRoute();
const router = useRouter();
// 添加tab
const addTab = () => {
  const {name, path, query} = route;
  const tab = {
    path: path,
    title: name,
    open: query.open,
    select: query.select,
  };
  tabStore.addTab(tabStore.tabList, tab);
};
// 唯一键
const activeKey = ref("");
watch(() => route.path, () => {
  activeKey.value = route.path;
  addTab();
});
// 跳转页面
const goTab = (item) => {
  router.push({
    name: item.title,
    query: {
      open: item.open,
      select: item.select,
    }
  });
  setTimeout(() => {
    router.go(0);
  }, 100);
}
// 删除tab
const removeTab = (path) => {
  // 判断是不是最后一页
  if (tabStore.tabList.length === 1) {
    return alert("最后一页");
  }
  const tabs = tabStore.tabList;
  let activePath = activeKey.value;
  // 判断唯一键是不是一样的
  if (activePath === path) {
    tabs.forEach((tab, index) => {
      if (tab.path === path) {
        const nextTab = tabs[index + 1] || tabs[index - 1];
        if (nextTab) {
          activePath = nextTab.path;
        }
      }
    })
  }
  activeKey.value = activePath;
  tabStore.tabList = tabs.filter(tab => tab.path !== path);
}
</script>

<template>
  <div class="jia-tabs">
    <div @click="goTab(item)" class="item jia-flex-center" v-for="(item, index) in tabStore.tabList" :key="index">
      <span :class="item.path === route.path ? 'active':''" style="margin-right: 5px">{{ item.title }}</span>
      <icon-close-circle-fill v-if="item.title !== '分析页'" class="jia-icon" @click.stop="removeTab(item.path)"/>
    </div>
  </div>
</template>

<style scoped lang="less">
.jia-tabs {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;

  div {
    height: 25px;
    padding: 3px 10px 3px 10px;
    border-radius: 3px;
    margin-right: 6px;
    cursor: pointer;
    background: var(--color-bg-1);

    .jia-icon:hover {
      opacity: .5;
    }
  }

  .item {
    animation: FadeInRight 1.5s;
  }

  .active {
    color: #2d8cf0;
  }
}
</style>